<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul class="cart-list" v-for="list in cartList" :key="list.id">
          <li class="cart-list-con1">
            <input
              type="checkbox"
              name="chk_list"
              :checked="!!list.isChecked"
              @change="changeIsChecked(list)"
            />
          </li>
          <li class="cart-list-con2">
            <img :src="list.imgUrl" />
            <div class="item-msg">
              {{ list.skuName }}
            </div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{ list.skuPrice }}</span>
          </li>
          <li class="cart-list-con5">
            <InputNumber
              :value="list.skuNum"
              :max="999"
              @input="updateCartNum(list, $event)"
            ></InputNumber>
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{ list.skuNum * list.skuPrice }}</span>
          </li>
          <li class="cart-list-con7">
            <a class="sindelet" @click="showDelCart(list.skuId)">删除</a>
            <br />
            <a href="#none">移到收藏</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" v-model="checkedAll" />
        <span>全选</span>
      </div>
      <div class="option">
        <a href="#none" @click="showDelCartAll">删除选中的商品</a>
        <a href="#none">移到我的关注</a>
        <a href="#none">清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">
          已选择
          <span>{{ isCheckedNum }}</span>
          件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ totalPrice }}</i>
        </div>
        <div class="sumbtn">
          <a class="sum-btn" @click="toTrade">结算</a>
        </div>
      </div>
    </div>
    <Dialog :isVisible.sync="isVisible">
      <template v-slot:header>提示</template>
      <template>
        是否要删除{{ isDelAll ? '所有已选中的' : '当前' }}商品?
      </template>
      <template v-slot:footer>
        <div class="btn-wrap">
          <button class="btn" @click="isVisible = false">取消</button>
          <button class="btn primary" @click="delGoodsConfirm">确认</button>
        </div>
      </template>
    </Dialog>
    <Dialog :isVisible.sync="isCheckedVisible">
      <template v-slot:header>提示</template>
      <template>请选择要结算的商品</template>
    </Dialog>
  </div>
</template>

<script>
import {
  reqShopCartList,
  reqSetListIsChecked,
  reqDeleteCart,
  reqAddToShopCart,
} from '@/api/shopcart'
import Dialog from '@/components/Dialog'
import InputNumber from '@/components/InputNumber'
import debounce from 'lodash/debounce'
export default {
  name: 'ShopCart',
  async mounted() {
    const res = await reqShopCartList()
    this.cartList = res[0] ? res[0].cartInfoList : []
  },
  components: {
    Dialog,
    InputNumber,
  },
  data() {
    return {
      cartList: [],
      isVisible: false,
      skuId: '',
      isDelAll: false,
      isCheckedVisible: false,
    }
  },
  methods: {
    async changeIsChecked(list) {
      // 发送请求修改isChecked,isChecked的值只能是0或1,但是list里的是true和false,所以要转化一下
      const isChecked = 1 - list.isChecked
      // 前端的数据的修改
      list.isChecked = isChecked
      await reqSetListIsChecked(list.skuId, isChecked)
    },
    // 点击删除,显示提示框
    showDelCart(skuId) {
      // 显示提示框
      this.isVisible = true
      // 保存skuId
      this.skuId = skuId
      // 使用删除请求时,用这个变量来表示是删除单个还是选中的
      this.isDelAll = false
    },
    // 点击删除选中的商品
    showDelCartAll() {
      // 显示提示框
      this.isVisible = true
      // 告诉删除请求,删除的是选中的
      this.isDelAll = true
    },
    // 点击确认按钮,发送删除请求
    async delGoodsConfirm() {
      // ***********删除选中**********
      if (this.isDelAll) {
        // 过滤出没选中的
        this.cartList = this.cartList.filter((list) => {
          // 用一个变量把商品的选中状态存起来
          const isChecked = !!list.isChecked
          // 如果是选中状态
          if (isChecked) {
            // 发请求删除
            reqDeleteCart(list.skuId)
          }
          // 返回非选中状态
          return !isChecked
        })
        this.isVisible = false
        return
      }
      // **********删除单个***********
      const { skuId } = this
      // 删除本地的数据
      this.cartList = this.cartList.filter((list) => list.skuId !== skuId)
      // 删除服务端的数据
      await reqDeleteCart(skuId)
      // 发送请求后,隐藏提示框,恢复滚动条
      this.isVisible = false
    },
    // 点击++或--修改商品的数量
    updateCartNum: debounce(function (list, num) {
      // 发送请求,修改数量
      // 注意要求传入id和数量,数量是指在原有基础上添加的数量,而不是框里的数量
      // num框里的,list.skuNum服务器里原有的
      // 更新服务端商品数量
      reqAddToShopCart(list.skuId, num - list.skuNum)
      // 更新客户端商品数量
      list.skuNum = num
    }, 500),
    // 未勾选商品的时候,不跳转
    toTrade() {
      if (this.isCheckedNum === 0) {
        this.isCheckedVisible = true
        return
      }
      this.$router.history.push('/trade')
    },
  },
  computed: {
    checkedAll: {
      // 遍历查找所有的数据的isChecked,返回=1的每一项,全是1则返回1,有一项不为1则是0
      // 初始的状态
      get() {
        return this.cartList.length
          ? this.cartList.every((list) => list.isChecked === 1)
          : 0
      },
      // 修改状态后
      set(val) {
        // 将所有商品的isChecked更新为和val相同
        const isChecked = val ? 1 : 0
        this.cartList.forEach((list) => {
          // 如何和修改的状态相同,则不修改
          if (list.isChecked === isChecked) return
          // 不同,则发送请求修改
          this.changeIsChecked(list)
        })
      },
    },
    // 选中的数量
    isCheckedNum() {
      // reduce:计算数组中的元素相加后的总和,pre初始值一般为0,c当前值
      return this.cartList.reduce((pre, c) => {
        return pre + (c.isChecked ? c.skuNum : 0)
      }, 0)
    },
    // 选中的总价
    totalPrice() {
      return this.cartList.reduce((pre, c) => {
        return pre + (c.isChecked ? c.skuNum * c.cartPrice : 0)
      }, 0)
    },
  },
}
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;

  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }

  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;

      & > div {
        float: left;
      }

      .cart-th1 {
        width: 25%;

        input {
          vertical-align: middle;
        }

        span {
          vertical-align: middle;
        }
      }

      .cart-th2 {
        width: 25%;
      }

      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }

    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;

      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;

        & > li {
          float: left;
        }

        .cart-list-con1 {
          width: 4.1667%;
        }

        .cart-list-con2 {
          width: 45%;

          img {
            width: 82px;
            height: 82px;
            float: left;
          }

          .item-msg {
            float: left;
            width: 350px;
            margin: 0 10px;
            line-height: 18px;
          }
        }

        .cart-list-con3 {
          width: 20.8333%;

          .item-txt {
            text-align: center;
          }
        }

        .cart-list-con4 {
          width: 12.5%;
        }

        .cart-list-con5 {
          width: 12.5%;

          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }

          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 33px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
        }

        .cart-list-con6 {
          width: 12.5%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 12.5%;

          a {
            color: #666;
          }
        }
      }
    }
  }

  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: 'Microsoft YaHei';
          background: #e1251b;
          overflow: hidden;
        }
      }
    }
  }
}
.btn {
  outline: none;
  border: 1px solid #ccc;
  font-size: 14px;
  padding: 8px 15px;
  margin-left: 15px;
  border-radius: 3px;
  cursor: pointer;
  background-color: #fff;
  &.primary {
    background-color: rgb(102, 177, 248);
    color: #fff;
  }
}
</style>
